<?php
//云片
class yunpian
{
    //发送短信
    public function sendSms($mobile,$code,$tplid,$apikey)
    {
        $tpl_value = "#code#=".$code;
        $data = $this -> Send_SMS($apikey,$tplid,$tpl_value,$mobile);
        $data = json_decode($data,true);

        if ( 0 == $data['code'] && "OK" == $data['msg'])
        {
            return true;
        }
        else
        {
            return false;

        }

    }
    
    //生成验证码
    public function getCode($len=4)
    {
        $chars = array('0','1','2','3','4','5','6','7','8','9');
        $char_txt = '';
        for($i = 0; $i < $len; $i++){
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    /**
     * 模板接口发短信
     * apikey 为云片分配的apikey
     * tpl_id 为模板id
     * tpl_value 为模板值
     * mobile 为接受短信的手机号
     */
    public function Send_SMS($apikey,$tpl_id,$tpl_value,$mobile){
        //$apikey = $this -> apikey;
        $url="http://yunpian.com/v1/sms/tpl_send.json";
        $encoded_tpl_value = urlencode("$tpl_value");  //tpl_value需整体转义
        $mobile = urlencode("$mobile");
        $post_string="apikey=$apikey&tpl_id=$tpl_id&tpl_value=$encoded_tpl_value&mobile=$mobile";
        return self::sock_post($url, $post_string);
    }
    /**
     * url 为服务的url地址
     * query 为请求串
     */
    static function sock_post($url,$query){
        $data = "";
        $info=parse_url($url);
        $fp=fsockopen($info["host"],80,$errno,$errstr,30);
        if(!$fp){
            return $data;
        }
        $head="POST ".$info['path']." HTTP/1.0\r\n";
        $head.="Host: ".$info['host']."\r\n";
        $head.="Referer: http://".$info['host'].$info['path']."\r\n";
        $head.="Content-type: application/x-www-form-urlencoded\r\n";
        $head.="Content-Length: ".strlen(trim($query))."\r\n";
        $head.="\r\n";
        $head.=trim($query);
        $write=fputs($fp,$head);
        $header = "";
        while ($str = trim(fgets($fp,4096))) {
            $header.=$str;
        }
        while (!feof($fp)) {
            $data .= fgets($fp,4096);
        }
        return $data;
    }
    /**
     * 模板选择
     * $mobile 为手机号码
     * $code 短信内容
     * $type 判断选择的模板
     * $apikey apikey
     */
    public function tplId($mobile,$code,$type,$apikey){
        //注册模板
        if($type==1){
            $tplid='1643546';
        }else if($type==2){
            //忘记密码模板
            $tplid='1216425';
        }else if($type==3){
            //修改账户资料
            $tplid='1348721';
        }else{
            $tplid='';
        }
         return $this ->sendSms($mobile,$code,$tplid,$apikey);
    }
}